"use strict";

//=============
// 引入程序依赖
//=============
import React, { Component } from "react" ;
import { connect } from "react-redux" ;
import { mapStateToProps, mapDispatchToProps } from "./RegisRedux" ;
import { Link, browserHistory } from "react-router" ;
import ErrorBar from "../../components/Public/ErrorBar/ErrorBar" ;

//交互依赖
import NetworkEngine from "../../utils/NetworkEngine" ;
import UrlManager from "../../utils/UrlManager" ;

//图片导入
import gantan from "../../static/img/h5/gantan.png";
import logo from "../../static/img/h5/logo.png";

class RegisContainer extends Component {
    constructor(props) {
        super(props);
        this.state = {
            code: "",
            error: "0",
            resetCodeFlag : "",//重新获取验证码标记
        }
    }
    componentDidMount(){
        this.state.clientIp = window.location.hostname;
        this.initGeetestFun();
    }

    //geetestAPI1
    initGeetestFun() {
        const _this = this;
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.initGeetest(),
            {
                userId: sessionStorage.getItem("id") ? sessionStorage.getItem("id") : "",
                clientType: "h5",
                clientIp: this.state.clientIp ? this.state.clientIp : null,
            }
        ).then(
            data => {
                let gtServerStatus = data.data.res.gt_server_status;
                let responseStr = data.data.res.responseStr;
                // let userId = data.data.res.userId;
                let geetestData = JSON.parse(responseStr);
                initGeetest({
                    gt: geetestData.gt,
                    challenge: geetestData.challenge,
                    new_captcha: geetestData.new_captcha, // 用于宕机时表示是新验证码的宕机
                    offline: !geetestData.success, // 表示用户后台检测极验服务器是否宕机，一般不需要关注
                    product: 'float',
                    width: "100%",
                    // bg_color:"custom",
                    // 更多配置参数请参见：http://www.geetest.com/install/sections/idx-client-sdk.html#config
                }, function (captchaObj) {
                    _this.state.captchaObj = captchaObj;
                    $("#submit1").click(function (e) {
                        var result = captchaObj.getValidate();
                        //验证不通过时
                        if (!result) {
                            if (_this.state.resetCodeFlag === 1) {
                                $(_this.refs.wrongCode).hide();
                                //点击重新获取,重新加载验证码,取消联动效果，需用户手动点击验证
                                captchaObj.reset();
                                _this.state.resetCodeFlag = 0;
                            } else {
                                _this.getPhoneCode(captchaObj,gtServerStatus);
                            }
                        } else {
                            //验证通过时,进入二次验证
                            _this.getPhoneCode(captchaObj,gtServerStatus);
                        }
                    });
                    // 将验证码加到id为captcha的元素里，同时会有三个input的值用于表单提交
                    captchaObj.appendTo("#captcha1");

                    captchaObj.onReady(function () {
                        $("#wait1").hide();
                    });

                    captchaObj.onSuccess(function() {
                        //清空验证码及其错误信息
                        _this.refs.code.value = '';
                        $(_this.refs.wrongCode).hide();
                        _this.showErrorInfo("hide");
                        _this.state.currentPhone = _this.refs.phone.value;
                    });
                });
            }
        ).catch(
            err => {

            }
        )
    }

    regisAccount(e){
        this.state.error = "0";
        this.checkDisplayName();
        this.checkPhone();
        this.checkPassword();
        this.checkCode();
        e.preventDefault() ;
        // console.log(this.state.error);
        if(this.state.error == "1"){
            return false;
        }else{
            let urlManager = new UrlManager();
            NetworkEngine(
                "POST",
                urlManager.regisAccount(),
                {
                    phone:this.refs.phone.value,
                    password:this.refs.password.value,
                    code:this.refs.code.value,
                    displayName:this.refs.displayName.value
                }
            ).then(
                data => {
                    if(data.data.status === "0"){
                        let _data = data.data.data ;
                        // console.log("===========账号信息===========",_data);
                        sessionStorage.setItem("id",_data.id) ;
                        sessionStorage.setItem("displayName",_data.displayName) ;
                        sessionStorage.setItem("phone",_data.phone) ;
                        sessionStorage.setItem("authenticationStatus",_data.authenticationStatus) ;
                        sessionStorage.setItem("headUrl","") ;
                        sessionStorage.setItem("userKeyId",_data.updatedUser);

                        browserHistory.push("/") ;
                    } else {
                        if (data.data.status === "1" && data.data.error_message) {
                            // $(this.refs.wrongCode).show();
                            // //验证码错误，刷新极验证信息.
                            this.state.captchaObj.reset();
                            this.state.resetCodeFlag = 0;
                            this.showErrorBar(data.data.error_message);
                            
                        }
                    }

                    // else if (data.data.status === "1") {
                    //     $(this.refs.wrongNull).hide();
                    //     $(this.refs.wrongPhone).hide();
                    //     $(this.refs.wrongMessage).show();
                    //     $(this.refs.phone).addClass("red-border");
                    // }else{
                    //     $(this.refs.displayName).removeClass("red-border");
                    //     $(this.refs.phone).removeClass("red-border");
                    //     $(this.refs.code).removeClass("red-border");
                    //     $(this.refs.password).removeClass("red-border");
                    // }
                }
            ).catch(
                err=>{

                }
            )
        }
        MtaH5.clickStat("H5_Regis_001");
    }

    // App注册昵称验证
    checkDisplayName() {
        if (this.refs.displayName.value === "") {
            $(this.refs.wrongName).show();
            $(this.refs.displayName).addClass("red-border");
            this.state.error = "1";
        } else {
            $(this.refs.wrongName).hide();
            $(this.refs.displayName).removeClass("red-border");
        }
    }

    // App注册手机验证
    checkPhone() {
        $(this.refs.wrongPhone).hide();
        $(this.refs.wrongNull).hide();
        $(this.refs.wrongMessage).hide();
        $(this.refs.phone).removeClass("red-border");
        let phone = this.refs.phone.value;
        var zhengzphone = /^1[34578]\d{9}$/;
        if(!zhengzphone.test(phone) && this.refs.phone.value === ""){
            $(this.refs.wrongPhone).hide();
            $(this.refs.wrongNull).show();
            $(this.refs.phone).addClass("red-border");
            $(this.refs.wrongMessage).hide();
            this.state.error = "1";
        } else if(!zhengzphone.test(phone)){
            $(this.refs.wrongPhone).show();
            $(this.refs.phone).addClass("red-border");
            $(this.refs.wrongNull).hide();
            $(this.refs.wrongMessage).hide();
            this.state.error = "1";
        }
    }

    // App注册密码校验
    checkPassword() {
        var str = this.refs.password.value;
        var reg=/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,12}$/;
        if (!reg.test(str)||this.refs.password.value === "") {
            $(this.refs.wrongPassword).show();
            $(this.refs.password).addClass("red-border");
            this.state.error = "1";

        }else{
            $(this.refs.wrongPassword).hide();
            $(this.refs.password).removeClass("red-border");
        }
    }

    // App注册验证码校验
    checkCode() {
        if (this.refs.code.value && this.refs.code.value.length != 6) {
            $(this.refs.wrongCode).show();
            $(this.refs.code).addClass("red-border");
            this.state.error = "1";
        } else {
            $(this.refs.wrongCode).hide();
            $(this.refs.code).removeClass("red-border");
        }
    }

    //后台验证手机信息，成功后发送验证码
    checkNotNullUser(verifyObj){
        let urlManager = new UrlManager();
        NetworkEngine(
            "post",
            urlManager.checkUserExist(),
            {
                phone: this.refs.phone.value,
                userId: sessionStorage.getItem("id") ? sessionStorage.getItem("id") : "",
                clientType: "h5",
                clientIp: this.state.clientIp ? this.state.clientIp : null,
                fnGeetestChallenge: verifyObj.geetest_challenge,
                fnGeetestValidate: verifyObj.geetest_validate,
                fnGeetestSeccode: verifyObj.geetest_seccode,
                gtServerStatus: verifyObj.gtServerStatus,
            }
        ).then(
            data => {
                let resStatus = data.data.res.status;
                if(resStatus == "0"){
                    //验证完成 发送验证码
                    this.sendCode();
                } else if (resStatus === "1") {
                    $(this.refs.wrongMessage).show();
                } else if (resStatus === "2") {
                    $(_this.refs.wrongCode).hide();
                    //极验证失败
                    this.state.captchaObj.reset();
                    this.showErrorInfo("极验证失败，请重新进行验证");
                    $(this.refs.wrongGeetest2).show();
                }

            }
        ).catch(
            err => {

            }
        )
    }
    // App手机验证码获取
    //前端手机校验
    getPhoneCode(captchaObj,gtServerStatus) {
        let result = captchaObj.getValidate();
        if(this.refs.phone.value === ""){
            $(this.refs.wrongNull).show();
            $(this.refs.wrongPhone).hide();
        }else{
            let phone = this.refs.phone.value;
            if (this.state.currentPhone && this.state.currentPhone != phone) {
                this.state.captchaObj.reset();
                this.showErrorInfo("注册信息已更改，请重新验证");
                return
            }
            var zhengzphone = /^1[34578]\d{9}$/;
            if (!zhengzphone.test(phone)) {
                $(this.refs.wrongPhone).show();
            } else if (!result) {
                // 极验证未通过
                this.showErrorInfo("请进行验证");
                // $('.geetest_radar_tip').click();
            } else {
                //验证通过时,进入二次验证
                result.gtServerStatus = gtServerStatus;
                //后台验证信息
                this.checkNotNullUser(result);
                if (this.state.resetCodeFlag === 0) {
                    this.state.resetCodeFlag = 1;
                }
            }
        }
        //埋点
        MtaH5.clickStat('Regis_001');
    }

    //展示极验证错误信息
    showErrorInfo(mes) {
        $(this.refs.wrongMessage).hide();
        if (mes === 'hide') {
            $(this.refs.wrongGeetest).hide();
        } else {
            $(this.refs.gtErrorMes).text(mes);
            $(this.refs.wrongGeetest).show();
        }
    }

    //errorBar展示
    showErrorBar(messageWord){
        this.setState({showError:true,errorWord:messageWord});
        setTimeout(()=>{this.setState({showError:false,errorWord:''})},3000);
    }

    sendCode() {
        let urlManager = new UrlManager();
        this.getyzm();
        NetworkEngine(
            "post",
            urlManager.getPhoneCode(),
            {
                phone: this.refs.phone.value,
            }
        ).then(
            data => {
                let _data = data.data.code;
                this.setState({code: _data});
                if (data.data.status === "1") {
                    $(this.refs.wrongPhone).show();
                    $(this.refs.phone).addClass("red-border")
                } else {
                    $(this.refs.wrongPhone).hide();

                }
                $(this.refs.phoneErrorMessage).text(data.data.error_message);
            }
        ).catch(
            err => {

            }
        )
    }

    getyzm() {
        // 计数变量
        var t = 60;
        var time = setInterval(daojishi, 1000);
        // 获得按钮对象
        var getyzm = this.refs.yzm;
        const _this = this;
        function daojishi() {
            if (t > 0) {
                t--;
                getyzm.innerText = t + "秒" + "重新获取";
                getyzm.disabled = true;
            } else {
                getyzm.innerText = "重新获取";
                clearInterval(time);//清理定时器
                getyzm.disabled = false;
                _this.state.resetCodeFlag = 1;
            }
        }
    }

    render(){
        return(
            <div className="login-form">
                <ErrorBar showError={this.state.showError} errorWord={this.state.errorWord}/>
                <div className="logo"><img src={logo} alt="咪吱logo"/></div>
                <div className="container">
                    <div className="input-f username">
                        <input type="text" className="input" ref="displayName" placeholder="昵称"
                               onBlur={this.checkDisplayName.bind(this)}/>
                        <div className="wrong" ref="wrongName">
                            <img src={gantan} alt="感叹"/>
                            <span>昵称不能为空</span>
                        </div>
                    </div>
                    <div className="input-f">
                        <input type="text" className="input wrong-f" ref="phone" placeholder="手机号" onBlur={this.checkPhone.bind(this)}/>
                        <div className="wrong" ref="wrongPhone">
                            <img src={gantan} alt="感叹"/>
                            <span>请输入正确的手机号</span>
                        </div>
                        <div className="wrong" ref="wrongMessage">
                            <img src={gantan} alt="感叹"/>
                            <span>该手机号已被注册</span>
                        </div>
                        <div className="wrong" ref="wrongNull">
                            <img src={gantan} alt="感叹"/>
                            <span>请输入需注册的手机号码</span>
                        </div>
                    </div>
                    <div className="form-geetest-item">
                        <div className="captcha">
                            <p id={"wait1"} className="show">正在加载验证码......</p>
                            <div id={"captcha1"}>
                            </div>
                        </div>
                        <div className="form-div-geetest">
                            <div className="form-wrong-geetest" ref="wrongGeetest">
                                <img className="wrong-img" src={gantan} alt="感叹"/>
                                <span className="wrong-geetest" ref="gtErrorMes">请点击进行验证</span>
                            </div>
                        </div>
                    </div>
                    <div className="input-f">
                        <div className="proving-f">
                            <input type="text" className="proving" ref="code" placeholder="手机验证码" onBlur={this.checkCode.bind(this)}/>
                            <button id="submit1"
                                    // onClick={this.getPhoneCode.bind(this)}
                                    className="proving-btn" ref="yzm">获取验证码</button>
                            <div className="wrong" ref="wrongCode">
                                <img src={gantan} alt="感叹"/>
                                <span ref="codeErrorMessage">验证码有误</span>
                            </div>
                        </div>
                    </div>
                    <div className="input-f">
                        <input type="password" className="input" ref="password"
                               placeholder="设置密码，6-12位字母和数字组成" maxLength={12} onBlur={this.checkPassword.bind(this)}/>
                        <div className="wrong" ref="wrongPassword">
                            <img src={gantan} alt="感叹"/>
                            <span ref="passwordErrorMessage">密码应该为6-12位字母和数字组成</span>
                        </div>
                    </div>
                    <button type="btn" className="form-btn orange-btn" onClick={this.regisAccount.bind(this)}>注册</button>
                    <span className="form-a margin-1">已经有账号，请<Link to="/login" className="logon">登录</Link></span>
                </div>
            </div>
        )
    }
}

const Regis = connect(mapStateToProps,mapDispatchToProps)(RegisContainer) ;

export { Regis as default } ;
